
#include "chapter1_2.h"

using namespace std;


/*
	input one file with data: like "he like c++ programming ............"
	
	support actions:
		Query( str_a)----------printf all matched line/colume
		Query( str_a || str_b)
		Query( str_a && str_b)
*/

typedef pair<int,int> Loc_P;
typedef pair<string , Loc_P> Loc;
typedef vector<Loc> VLoc;

class BaseQuery
{
public:
	virtual void eval() = 0;
	BaseQuery( ) { if(NULL == pv_loc) pv_loc= new VLoc;};
	//BaseQuery( VLoc *loc ) { pv_loc = loc; };
	~BaseQuery( ) { };

	void buildMap( string filename);

private:
	
	static VLoc *pv_loc;	// save all word and its location(line/column)


};

class StrQuery : public BaseQuery
{
public:
	StrQuery() {};
	~StrQuery() {};
	void eval( ) {};


};

class AndQuery : public BaseQuery
{
public:
	AndQuery() {};
	~AndQuery() {};
	void eval() {};

};

class OrQuery : public BaseQuery
{
public:
	void eval();

};

string::size_type getword(string *pstr, vector<string> *pv_word);

VLoc *BaseQuery::pv_loc = NULL;
void BaseQuery::buildMap(string file_name )
{
	ifstream infile(file_name.c_str(), ios::in);
	if(infile == NULL)
		_DebugPrint("err open input rfile!\n"), exit(-1);

	vector<string> v_line_str;
	string line_txt;
	int line = 0;
	
	vector<string> v_word;
	VLoc vloc;
	/* build line string vector */
	while(getline(infile, line_txt, '\n') > 0)
	{
		v_line_str.push_back(line_txt);
		line++;
		v_line_str.push_back(line_txt);
		getword(&line_txt, &v_word);

		int row = 0;
		 vector<string>::iterator Iter;
		 for(Iter = v_word.begin(); Iter < v_word.end(); Iter++)
		{
			Loc loc;
			row++;
			loc.first = *Iter;
			loc.second.first = line;
			loc.second.second = row;			
			pv_loc->push_back(loc);
		}
		 v_word.clear( );
	
	}
}
void test_query()
{
	BaseQuery *pbq;
	StrQuery strQ;

	pbq = &strQ;
	pbq->buildMap("infile.txt");

	AndQuery andQ;
	pbq = &andQ;

}

string::size_type getword(string *pstr, vector<string> *pv_word)
{
	string::size_type pos = 0,word_num = 0, line_len = pstr->length();

	pstr->insert(line_len, " ");
	line_len++;

	while(-1 != (pos = pstr->find( ' ')))
	{
		char word[64] = {0,};
		if(pos == 0){
			*pstr = pstr->substr( 1 );continue;
		}
		pstr->copy(word, pos, 0); 
		pv_word->push_back(word);
		word_num++;		
		line_len -= pos;
		*pstr = pstr->substr(pos);
	}

	return word_num;
}